<?php
class Controller_Admin_Download extends Controller_Form
{
    public function __construct ($req, $res)
    {
        $this->_form_type = 'download';
        parent::__construct($req, $res);

        $this->_list_where = array(
            array('type',  '=', 'popular_game'),
        );

        $this->_sort_extra_columns = array(
            array('changed', DB::expr('curdate()')),
        );
    }

    public function action_index ()
    {
        $this->action_list();
    }

    public function action_create ()
    {
        $post = $this->request->post();
        if (! empty($post))
        {
            $pname = Arr::get($post, 'packageName');
            $downs = Arr::get($post, 'downloadCount');

            if (empty($pname) || empty($downs))
            {
                $this->request->redirect('/admin/download/create');
                return;
            }
                
            $id = API_Package::reset_downloads($pname, $downs);
            if ($id > 0)
                $url = "/admin/package/detail/$id";
            else
                $url = '/admin/download/create';
                

            $this->request->redirect($url);
        }
        else
        {
            parent::action_create();
        }

    }

    public function action_update ($nid)
    {
        $post = $this->request->post();
        if (! empty($post))
        {
            $this->rebuild_post_data($post);
            $this->_form_data = $post;
        }
        else
        {
            $data = Form_Data::detail($this->_form_type, $nid); 
            $this->_form_data = $data;
        }

        parent::action_update($nid);
    }

    public function action_detail ($nid)
    {
        $data = Form_Data::detail($this->_form_type, $nid); 
        $this->_form_data = $data;

        parent::action_detail($nid);
    }

    public function detail_filter_config_data (& $arr_config)
    {
        foreach ($arr_config as & $rs)
        {
            if ($rs['input_name'] == 'name')
            {
                $rs['class'] = 'line';
                $rs['input_type'] = 'text';
            }
        }
    }

    private function rebuild_post_data (& $post)
    {
        $pname = Arr::get($post, 'packageName');
        if (empty($pname))
            throw new Exception_Invalid("包名不能为空");

        $pinfo = API_Market::appinfo($pname);
        $post['name'] = Arr::get($pinfo, 'name');
        $post['cid']  = (int) Arr::get($pinfo, 'categoryId');
        $post['serialize_data'] = serialize($pinfo);
        $post['block_id'] = Arr::get($pinfo, 'block_id');
    }
}
